const request = require("request");
const path = require('path');
const headers = require("./headers").headers;
const express = require("express");
const utils = require("./utils");
const app = express();
const port = 3000;

app.get(`/`, (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
  });
app.get("/selectTrian", (req, res) => {
  let body = req.query;
  let options = {
    url:
      "https://kyfw.12306.cn/otn/leftTicket/queryA?leftTicketDTO.train_date=" +
      body.train_date +
      "&leftTicketDTO.from_station=" +
      body.from_station +
      "&leftTicketDTO.to_station=" +
      body.to_station +
      "&purpose_codes=ADULT",
    headers: headers,
  };
  request(options, (error, response, body) => {
    if (!error && response.statusCode == 200) {
      const info = JSON.parse(body);
      res.json(utils.initTrain(info.data.result));
    } else {
      res.status(500).json({ error: "参数错误" });
    }
  });
});
app.get("/selectTrianInfo",(req,res)=>{
    let body = req.query;
    let train_no = body.train_no;
    let depart_date = body.depart_date;
    let from_station_telecode = body.from_station_telecode
    let to_station_telecode = body.to_station_telecode
    let options = {
        url :
        "https://kyfw.12306.cn/otn/czxx/queryByTrainNo?train_no=" +
        train_no +
        "&from_station_telecode="+from_station_telecode+"&to_station_telecode="+to_station_telecode+"&depart_date="+depart_date,
        headers: headers,
      };
      console.log(options.url);
      request(options, (error, response, body) => {
        if (!error && response.statusCode == 200) {
          const info = JSON.parse(body);
          res.json(info.data);
        } else {
          res.status(500).json({ error: "参数错误" });
        }
      });
})
app.use(express.static(path.join(__dirname, 'public')));//__dirname为程序执行时的绝对路径。
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

// let getData = () => {
//   request(options, (error, response, body) => {
//     if (!error && response.statusCode == 200) {
//       const info = JSON.parse(body);
//       initTrain(info.data.result)

//     }
//   });
// };

// getData();
